import React, { useState, useEffect } from 'react';
import { Form, Input, Button, message, Card, Typography, Space } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '@/stores/authStore';

const { Title, Text } = Typography;

interface LoginForm {
  email: string;
  password: string;
}

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const { login, isAuthenticated, user, token } = useAuthStore();

  // 检查是否已经登录
  useEffect(() => {
    console.log('📍 登录页面状态检查:', { 
      isAuthenticated, 
      hasUser: !!user, 
      hasToken: !!token,
      pathname: location.pathname 
    });
    
    if (isAuthenticated && user) {
      console.log('🔄 用户已登录，重定向到仪表盘');
      navigate('/dashboard', { replace: true });
    }
  }, [isAuthenticated, user, token, navigate, location.pathname]);

  const handleSubmit = async (values: LoginForm) => {
    setLoading(true);
    console.log('📝 提交登录表单:', { email: values.email });
    
    try {
      await login(values.email, values.password);
      console.log('✅ 登录成功，准备跳转');
      message.success('登录成功');
      
      // 稍微延迟一下，确保状态更新完成
      setTimeout(() => {
        console.log('🔄 执行路由跳转到仪表盘');
        navigate('/dashboard', { replace: true });
      }, 100);
      
    } catch (error: any) {
      console.error('❌ 登录失败:', error);
      message.error(error?.response?.data?.message || '登录失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        {/* Logo和标题 */}
        <div className="text-center">
          <div className="flex justify-center mb-6">
            <div className="w-16 h-16 flex items-center justify-center">
              <img 
                src="/logo.png" 
                alt="XLCIG Logo" 
                className="w-full h-full object-contain"
                onError={(e) => {
                  e.currentTarget.style.display = 'none';
                  const nextElement = e.currentTarget.nextElementSibling as HTMLElement;
                  if (nextElement) {
                    nextElement.style.display = 'flex';
                  }
                }}
              />
              <div 
                className="w-14 h-14 bg-gradient-to-r from-blue-600 to-blue-800 rounded-lg flex items-center justify-center hidden"
                style={{ display: 'none' }}
              >
                <span className="text-white font-bold text-xl">XL</span>
              </div>
            </div>
          </div>
          <Title level={2} className="text-gray-900">
            XLCIG 管理后台
          </Title>
          <Text type="secondary" className="text-base">
            请登录您的管理员账户
          </Text>
        </div>

        {/* 登录表单 */}
        <Card className="border-0 shadow-lg">
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            size="large"
            requiredMark={false}
          >
            <Form.Item
              name="email"
              label="账号"
              rules={[
                { required: true, message: '请输入账号' },
              ]}
            >
              <Input
                prefix={<UserOutlined className="text-gray-400" />}
                placeholder="邮箱/用户名/手机号"
                autoComplete="username"
              />
            </Form.Item>

            <Form.Item
              name="password"
              label="密码"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码长度至少6位' },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined className="text-gray-400" />}
                placeholder="请输入密码"
                autoComplete="current-password"
              />
            </Form.Item>

            <Form.Item className="mb-0">
              <Space direction="vertical" className="w-full" size="large">
                <Button
                  type="primary"
                  htmlType="submit"
                  className="w-full h-12 text-base font-medium"
                  loading={loading}
                >
                  登录
                </Button>
                
                <div className="text-center">
                  <Text type="secondary" className="text-sm">
                    系统管理员登录入口
                  </Text>
                </div>
              </Space>
            </Form.Item>
          </Form>
        </Card>

        {/* 底部信息 */}
        <div className="text-center">
          <Text type="secondary" className="text-xs">
            © 2024 XLCIG. All rights reserved.
          </Text>
        </div>
      </div>
    </div>
  );
};

export default Login; 